using System.Web.Mvc;
using System.Linq;
using Orchard.Localization;
using Orchard;
using Orchard.Themes;
using Orchard.Mvc;
using Orchard.DisplayManagement;
using Orchard.Security;
using Rework.CommerceHistory.Services;
using Orchard.Fields.Fields;
using Orchard.Environment.Extensions;

namespace Rework.CommerceHistory.Controllers {
    [OrchardFeature("Rework.CommerceHistory")]
    [Authorize]
    public class CommerceHistoryController : Controller {
        public IOrchardServices Services { get; set; }
        private readonly IWorkContextAccessor _wca;
        private readonly dynamic _shapeFactory;
        private readonly ICommerceHistory _commerceHistory;

        public CommerceHistoryController(
            IOrchardServices services
            , IShapeFactory shapeFactory
            , IWorkContextAccessor wca
            , ICommerceHistory commerceHistory) {
            Services = services;
            _shapeFactory = shapeFactory;
            _wca = wca;
            _commerceHistory = commerceHistory;
            
            T = NullLocalizer.Instance;
            _user = Services.WorkContext.CurrentUser;
        }

        public Localizer T { get; set; }
        private IUser _user { get; set; }

        [Themed]
        [OutputCache(Duration = 0)]
        public ActionResult Index() {
            _wca.GetContext().Layout.IsCommerceHistoryPage = true;
            return new ShapeResult(this, BuildCommerceHistoryShape());
        }

        private dynamic BuildCommerceHistoryShape(bool isSummary = false) {
            dynamic shape = _shapeFactory.CommerceHistory();

            var productQuantities = _commerceHistory.GetProducts(_user.Id).ToList();
            var productShapes = productQuantities.Select(
                    productQuantity => _shapeFactory.CommerceHistoryItem(
                        Quantity: productQuantity.Quantity,
                        Price: productQuantity.Price,
                        Product: productQuantity.Product,
                        ProductImage: ((MediaPickerField)productQuantity.Product.Fields.FirstOrDefault(f => f.Name == "ProductImage")),
                        Title: Services.ContentManager.GetItemMetadata(productQuantity.Product).DisplayText,
                        IsPaymentConfirmed: productQuantity.IsPaymentConfirmed
                        )
                ).ToList();

            shape.CommerceHistoryItems = productShapes;

            if (isSummary) {
                shape.Metadata.Alternates.Add("CommerceHistory_Summary");
            }
            return shape;
        }
    }
}
